<template>
  <div class="timer-component-container">

    <!-- 1. 遮罩层 (仅在打开设置时显示，用于点击外部关闭) -->
    <div
      v-if="viewState === 'setup'"
      class="transparent-overlay"
      @click="closeSetup"
    ></div>

    <!-- 2. 按钮与设置卡片的容器 (相对定位) -->
    <div class="relative-wrapper">

      <!-- 设置卡片 (Popover) - 在按钮上方 -->
      <transition name="pop-scale">
        <div v-if="viewState === 'setup'" class="setup-popup">
          <div class="popup-arrow"></div> <!-- 小三角 -->

          <div class="popup-header">
            <span>设定时间</span>
            <!-- 快捷关闭 -->
          </div>

          <!-- 输入区 -->
          <div class="time-inputs">
            <div class="input-item">
              <input type="number" v-model.number="form.h" placeholder="0" @input="limitInput($event, 'h')">
              <label>时</label>
            </div>
            <span class="colon">:</span>
            <div class="input-item">
              <input type="number" v-model.number="form.m" placeholder="0" @input="limitInput($event, 'm')">
              <label>分</label>
            </div>
            <span class="colon">:</span>
            <div class="input-item">
              <input type="number" v-model.number="form.s" placeholder="0" @input="limitInput($event, 's')">
              <label>秒</label>
            </div>
          </div>

          <!-- 快捷选项 (更紧凑) -->
          <div class="presets-row">
            <button v-for="t in [1, 3, 5, 10]" :key="t" @click="setPreset(t)">{{ t }}分</button>
          </div>

          <!-- 底部动作 -->
          <div class="popup-footer">
            <button class="btn-cancel" @click="closeSetup">取消</button>
            <button class="btn-start" @click="startTimer">开始计时</button>
          </div>
        </div>
      </transition>

      <!-- 核心触发按钮 (倒计时开始后隐藏) -->
      <transition name="fade-scale">
        <button
          v-if="viewState !== 'running'"
          class="main-trigger-btn"
          :class="{ 'active': viewState === 'setup' }"
          @click="toggleSetup"
        >
          <i class="fa-solid fa-alarm-clock"></i> 计时器
        </button>
      </transition>
    </div>

    <!-- 3. 灵动岛 (Fixed Top) - 倒计时开始后接管 -->
    <transition name="island-slide">
      <div v-if="viewState === 'running'" class="island-container">
        <div
          class="dynamic-island"
          :class="{ expanded: isExpanded }"
          ref="island"
        >
          <!-- 胶囊收起态 -->
          <div v-if="!isExpanded" class="compact-view" @click="toggleExpand">
            <div class="c-icon-box">
              <svg class="progress-ring" viewBox="0 0 24 24">
                <circle class="bg-ring" cx="12" cy="12" r="10"></circle>
                <circle class="active-ring" :style="ringStyle" cx="12" cy="12" r="10"></circle>
              </svg>
            </div>
            <span class="c-time">{{ formattedTime }}</span>
          </div>

          <!-- 胶囊展开态 -->
          <div v-if="isExpanded" class="expanded-view" @click.stop>
            <div class="ex-header">
              <span>倒计时</span>
              <span class="status-txt">{{ isPaused ? '已暂停' : '进行中' }}</span>
            </div>
            <div class="ex-big-time">{{ formattedTime }}</div>
            <div class="ex-controls">
              <button class="ctrl-btn stop" @click="stopTimer">✕</button>
              <button class="ctrl-btn play" @click="togglePause">
                {{ isPaused ? '▶' : 'II' }}
              </button>
            </div>
          </div>
        </div>
      </div>
    </transition>

  </div>
</template>

<script>
export default {
  name: 'PopoverTimer',
  data() {
    return {
      viewState: 'idle', // 'idle' | 'setup' | 'running'
      isExpanded: false,
      isPaused: false,

      form: { h: '', m: '', s: '' },

      totalSeconds: 0,
      remainingSeconds: 0,
      timerInterval: null,
      circumference: 2 * Math.PI * 10
    }
  },
  computed: {
    formattedTime() {
      const h = Math.floor(this.remainingSeconds / 3600)
      const m = Math.floor((this.remainingSeconds % 3600) / 60)
      const s = this.remainingSeconds % 60
      const pad = n => (n < 10 ? '0' + n : n)
      return h > 0 ? `${h}:${pad(m)}:${pad(s)}` : `${m}:${pad(s)}`
    },
    ringStyle() {
      const offset = this.circumference - (this.remainingSeconds / this.totalSeconds) * this.circumference
      return {
        strokeDasharray: `${this.circumference} ${this.circumference}`,
        strokeDashoffset: isNaN(offset) ? 0 : offset
      }
    }
  },
  beforeDestroy() {
    document.removeEventListener('click', this.handleClickOutside)
    // 同时也清除可能存在的定时器
    if (this.timerInterval) clearInterval(this.timerInterval)
  },
  mounted() {
    document.addEventListener('click', this.handleClickOutside)
  },

  methods: {
    // --- UI 逻辑 ---
    toggleSetup() {
      if (this.viewState === 'setup') {
        this.closeSetup()
      } else {
        this.viewState = 'setup'
      }
    },
    closeSetup() {
      this.viewState = 'idle'
      this.resetForm() // 可选：关闭是否清空数据
    },

    // --- 计时器逻辑 ---
    startTimer() {
      const h = parseInt(this.form.h) || 0
      const m = parseInt(this.form.m) || 0
      const s = parseInt(this.form.s) || 0
      const total = h * 3600 + m * 60 + s

      if (total <= 0) return

      this.totalSeconds = total
      this.remainingSeconds = total
      this.isPaused = false
      this.isExpanded = false

      // 状态切换：按钮消失，灵动岛出现
      this.viewState = 'running'
      this.runInterval()
    },

    handleClickOutside(event) {
      // 只有在 "运行状态" 且 "已展开" 时才需要检测
      if (this.viewState === 'running' && this.isExpanded) {

        // 获取灵动岛的 DOM 元素
        const islandEl = this.$refs.island

        // 判断：如果灵动岛存在，且点击的目标不在灵动岛内部
        if (islandEl && !islandEl.contains(event.target)) {
          this.isExpanded = false // 收起胶囊
        }
      }
    },

    runInterval() {
      clearInterval(this.timerInterval)
      this.timerInterval = setInterval(() => {
        if (!this.isPaused) {
          if (this.remainingSeconds > 0) {
            this.remainingSeconds--
          } else {
            this.finishTimer()
          }
        }
      }, 1000)
    },

    stopTimer() {
      clearInterval(this.timerInterval)
      this.viewState = 'idle' // 回到按钮
    },

    togglePause() {
      this.isPaused = !this.isPaused
    },

    finishTimer() {
      clearInterval(this.timerInterval)
      alert('⏰ 时间到！')
      this.viewState = 'idle' // 回到按钮
      this.resetForm()
    },

    // --- 辅助 ---
    toggleExpand() {
      this.isExpanded = true
    },
    setPreset(min) {
      this.form = { h: '', m: min, s: '' }
    },
    resetForm() {
      this.form = { h: '', m: '', s: '' }
    },
    limitInput(e, k) {
      if (e.target.value.length > 2) this.form[k] = parseInt(e.target.value.slice(0, 2))
    }
  }
}
</script>

<style scoped>
/* 变量 */
.timer-component-container {
  --pop-bg: #1c1c1e;
  --pop-text: #ffffff;
  --accent: #FF9F0A;
  --danger: #FF453A;
  --island-bg: #000000;

  font-family: -apple-system, sans-serif;
  display: inline-block; /* 作为一个行内块级组件 */
}

/* 1. 遮罩层 (透明) */
.transparent-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 99;
}

/* 2. 相对定位容器 */
.relative-wrapper {
  position: relative;
  display: flex;
  justify-content: center;
}

/* 核心按钮 */
.main-trigger-btn {
  background: var(--accent);
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 30px;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 8px;
  box-shadow: 0 4px 10px rgba(255, 159, 10, 0.3);
  transition: transform 0.2s, opacity 0.3s;
  z-index: 100; /* 保证按钮在遮罩之上 */
  position: relative;
}

.main-trigger-btn:active {
  transform: scale(0.95);
}

.main-trigger-btn.active {
  transform: scale(0.95);
  opacity: 0.8;
}

/* 3. 设置弹窗 (Popover) */
.setup-popup {
  position: absolute;
  bottom: 100%; /* 位于上方 */
  left: 50%;
  transform: translateX(-50%); /* 居中 */
  margin-bottom: 12px;

  width: 260px;
  background: var(--pop-bg);
  color: var(--pop-text);
  border-radius: 18px;
  padding: 16px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.5);
  z-index: 101;
  display: flex;
  flex-direction: column;
}

/* 小三角 */
.popup-arrow {
  position: absolute;
  bottom: -6px;
  left: 50%;
  margin-left: -6px;
  width: 12px;
  height: 12px;
  background: var(--pop-bg);
  transform: rotate(45deg);
}

.popup-header {
  font-size: 13px;
  color: #888;
  text-align: center;
  margin-bottom: 12px;
}

/* 输入框 */
.time-inputs {
  display: flex;
  justify-content: center;
  align-items: flex-end;
  gap: 5px;
  margin-bottom: 15px;
}

.input-item {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.input-item input {
  width: 44px;
  height: 44px;
  background: #2c2c2e;
  border: none;
  border-radius: 8px;
  color: white;
  font-size: 20px;
  text-align: center;
}

.input-item label {
  font-size: 10px;
  color: #666;
  margin-top: 4px;
}

.colon {
  font-size: 20px;
  padding-bottom: 20px;
  color: #666;
}

/* 预设 */
.presets-row {
  display: flex;
  justify-content: space-between;
  gap: 8px;
  margin-bottom: 15px;
}

.presets-row button {
  flex: 1;
  background: #2c2c2e;
  color: #fff;
  border: none;
  padding: 6px 0;
  border-radius: 6px;
  font-size: 12px;
  cursor: pointer;
}

.presets-row button:hover {
  background: #3a3a3c;
}

/* 底部按钮 */
.popup-footer {
  display: flex;
  gap: 10px;
}

.popup-footer button {
  flex: 1;
  padding: 10px;
  border-radius: 10px;
  border: none;
  font-size: 14px;
  font-weight: 600;
  cursor: pointer;
}

.btn-cancel {
  background: rgba(118, 118, 128, 0.24);
  color: #8e8e93;
}

.btn-start {
  background: var(--accent);
  color: white;
}


/* 4. 灵动岛 (Running State) */
.island-container {
  position: fixed;
  top: 10px;
  left: 0;
  right: 0;
  display: flex;
  justify-content: center;
  z-index: 2000;
  pointer-events: none; /* 容器不挡鼠标，内部岛屿挡 */
}

.dynamic-island {
  pointer-events: auto;
  background: var(--island-bg);
  width: 180px;
  height: 34px;
  border-radius: 17px;
  padding: 0 5px;
  display: flex;
  align-items: center;
  box-shadow: 0 5px 20px rgba(0, 0, 0, 0.3);
  transition: all 0.5s cubic-bezier(0.175, 0.885, 0.32, 1.275);
  cursor: pointer;
  overflow: hidden;
}

.dynamic-island.expanded {
  width: 320px;
  height: 140px;
  border-radius: 35px;
  flex-direction: column;
  padding: 20px;
  cursor: default;
}

/* Compact View */
.compact-view {
  width: 100%;
  display: flex;
  align-items: center;
  justify-content: space-between;
  transition: opacity 0.2s;
}

.dynamic-island.expanded .compact-view {
  display: none;
}

.c-icon-box {
  width: 22px;
  height: 22px;
  margin-right: 8px;
}

.progress-ring {
  transform: rotate(-90deg);
  width: 100%;
  height: 100%;
}

.bg-ring {
  stroke: rgba(255, 159, 10, 0.3);
  fill: none;
  stroke-width: 3;
}

.active-ring {
  stroke: var(--accent);
  fill: none;
  stroke-width: 3;
  stroke-linecap: round;
  transition: stroke-dashoffset 1s linear;
}

.c-time {
  color: var(--accent);
  font-weight: 600;
  font-size: 14px;
  font-variant-numeric: tabular-nums;
  margin-right: 4px;
}

/* Expanded View */
.expanded-view {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  opacity: 0;
  animation: fadeIn 0.4s forwards 0.1s;
  position: relative;
}

@keyframes fadeIn {
  to {
    opacity: 1;
  }
}

.ex-header {
  display: flex;
  justify-content: space-between;
  color: #666;
  font-size: 12px;
  margin-bottom: 10px;
}

.status-txt {
  color: var(--accent);
}

.ex-big-time {
  font-size: 42px;
  color: var(--accent);
  font-weight: 500;
  font-variant-numeric: tabular-nums;
  text-align: center;
  margin-bottom: 15px;
  line-height: 1;
}

.ex-controls {
  display: flex;
  justify-content: center;
  gap: 20px;
}

.ctrl-btn {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  border: none;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 16px;
  color: white;
  cursor: pointer;
}

.ctrl-btn.stop {
  background: rgba(255, 69, 58, 0.2);
  color: var(--danger);
}

.ctrl-btn.play {
  background: rgba(255, 255, 255, 0.2);
}

.ex-close {
  position: absolute;
  top: -5px;
  right: -5px;
  background: none;
  border: none;
  color: #555;
  cursor: pointer;
  padding: 5px;
}

.ex-close:hover {
  color: #888;
}

/* 动画 Transition */
.pop-scale-enter-active, .pop-scale-leave-active {
  transition: all 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275);
}

.pop-scale-enter, .pop-scale-leave-to {
  opacity: 0;
  transform: translateX(-50%) scale(0.8) translateY(10px);
}

.fade-scale-enter-active, .fade-scale-leave-active {
  transition: all 0.3s ease;
}

.fade-scale-enter, .fade-scale-leave-to {
  opacity: 0;
  transform: scale(0.5);
}

.island-slide-enter-active {
  animation: slideDown 0.5s cubic-bezier(0.175, 0.885, 0.32, 1.275);
}

.island-slide-leave-active {
  transition: opacity 0.3s;
  opacity: 0;
}

@keyframes slideDown {
  from {
    transform: translateY(-150%);
    opacity: 0;
  }
  to {
    transform: translateY(0);
    opacity: 1;
  }
}
</style>
